<?php
/*
+ --------------------------------------------------- +
|  Ineo Article Manager - Version 2.x
|  Copyright 2006-2007, Dan Cryer and William McGann
+ --------------------------------------------------- +

Ineo Article Manager is free software; you can redistribute it and/or modify
it under the terms of version 3 of the GNU General Public License as published by
the Free Software Foundation.

Ineo Article Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Ineo; see the file License.txt.  If not, write to
the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.

*/

/**
* Ineo - Modules - Dynamic
*  
* This module handles all front-end actions related to "AJAX" Requests.
*
* @package		Ineo
* @subpackage   Modules
* @author		Dan Cryer & William McGann
* @copyright	Dan Cryer & William McGann
* @version		1.0.0
*/
class ineo_mod_dynamic
{
    /**
    * IPSClass Reference - Always passed by the core class on creation.
    */
    var $ipsclass;
    
    /**
    * Core class reference.
    */
    var $core;

    function module_init()
    {
		$this->core->load_library('global');
		$this->lib_global =& $this->core->global;
    }

	/**
	* Send Ajax Response
	*
	* This replaces our previous  print then die, to make sure that ajax_utf8_safe() is called, 
	* which makes sure that special characters are not destroyed by being sent as the wrong
	* charset.
	*/
	function send_ajax_response( $response_string )
	{
		// make sure ajax requests are utf8 safe:
		$this->lib_global->ajax_utf8_safe();
		
		// Replace &ineo; with ineo_page_title
		$response_string =& str_replace('&ineo;',$this->ipsclass->vars['ineo_page_title'],$response_string);
		
		// Send the response:
		print $response_string;
		
		// End execution:
		die;
	}
    
    /**
    * AJAX Quick Search - So sexy it hurts.
    * @todo Template calls are IPB specific. Switch to core. :D
    */
    function search()
    {
    	// Be lazy, make shortcut:
    	$db =& $this->ipsclass->DB;
		
		// Replace under scores with spaces...( I forget why :( )
		$this->ipsclass->input['q'] = str_replace( '_' , ' ', $this->ipsclass->input['q'] );
		
		// BOOM! Explode the string into individual words in an array:
		$words = explode( ' ' , $this->ipsclass->input['q'] );
		
		// KABAM! Implode with % for a LIKE query, it's dirty - but I like it.
		$like = '%' . implode( '%' , $words ) . '%';
		
		// Do a query that checks for all of the articles where the TITLE or CONTENT matches our LIKE
		$q = $db->simple_construct( array('select' => 'a.*','from'   => array( 'ineo_articles' => 'a' ),'where' => 'a.article_is_queued = \'0\' AND (a.article_title LIKE ( \'' . $like . '\' ) OR a.article_description LIKE ( \'' . $like . '\' ) OR c.content_content LIKE (\'' . $like . '\') )','add_join' => array( 1 => array(	'type' => 'left','from' => array('ineo_content' => 'c'), 'where' => 'c.content_id=a.article_content'))));
		
		$db->simple_order( 'a.article_edited_date DESC' );
		
		//TODO TODO TODO! Check that ineo_qs_max is an actual var settin'
		$db->simple_limit( $this->ipsclass->vars['ineo_qs_max'] );
		$res = $db->simple_exec(); 
				
		$results = '';
		// Looooooooooooop and build list:
		while( $result = $db->fetch_row( $res ) )
		{
			// Make the date from timestamp:
			$result['article_date'] = $this->ipsclass->get_date($result['article_edited_date'],'');
			$result['article_url'] = $this->core->libs['global']->make_article_url( $result['article_id'], $result['article_text_id'] );
			$results .= $this->ipsclass->compiled_templates['global']->quick_search_result( $result );
		}
		
	    $results = $this->ipsclass->compiled_templates['global']->quick_search( $results );
	
		$this->send_ajax_response($results);
    }

	function vcheck()
	{ 
		if( md5($this->ipsclass->input['vc']) == 'f9260735315e01448823722a3c054349' )
		{
			print '{customer.id}-'.$this->core->version['rev_id'];
			die;
		}
		else
		{
			header('location: ' . $this->core->base_url);
		} 
	}

	// None-Ajax Topic Creation:
	function forward_to_create_topic()
	{
		$id = $this->create_topic();
		
		if( $id == false )
		{
			$this->ipsclass->boink_it( $this->core->base_url.'showarticle='.intval( $this->ipsclass->input['id'] ) );
		}
		else
		{
			$this->ipsclass->boink_it($this->ipsclass->base_url.'showtopic='.$id);
		}
	}
	
	function create_topic()
	{	
		// If this feature is disabled, then we'd better not continue:
		if( $this->ipsclass->vars['ineo_dtopics'] )
		{
			if( $this->ipsclass->input['op'] == 'create_topic' )
			{
				$this->send_ajax_response('');
			}
			else
			{
				return false;
			}
		}	
		
		// Create the topic. Hopefully this will return an array. If it does not, something
		// is wrong!
		$var = $this->core->libs['global']->create_discussion_topic($this->ipsclass->input['id']);
		if( !is_array($var) )
		{
			if( $this->ipsclass->input['op'] == 'create_topic' )
			{
				$this->send_ajax_response($var);
			}
			else
			{
				return false;
			}
		}
		else
		{
			$title = $var['title'];
			$id    = $var['id'];
			
			if( $this->ipsclass->input['op'] == 'create_topic' )
			{
				$topic = '<b>'.$this->ipsclass->lang['ineo_discuss_on']."</b> <a id='ineo-topic-view' href='{$this->ipsclass->base_url}showtopic={$id}'>{$title}</a>";
				$this->send_ajax_response($topic);
			}
			else
			{
				return $id;
			}
		}
	}
	
	function topic_quickview()
	{
		if ( $this->ipsclass->member['g_ineo_view'] == '0' )
		{
		  die();
		}
		
		$tid = intval($this->ipsclass->input['tid']);
		$aid = intval($this->ipsclass->input['aid']);
		
    $this->core->load_template('articles');
    
		$select = array( 
									'select' => 'p.*,m.members_display_name,t.forum_id',
									'from'   => array( 'posts' => 'p' ),
									'where' => 'p.topic_id = ' . $tid . ' AND p.queued = 0',
									'add_join' => array( 1 => array(
															'type' => 'left',
															'from' => array( 'members' => 'm' ),
															'where' => 'm.id = p.author_id',
															),
															2 => array(
															'type' => 'left',
															'from' => array( 'topics' => 't' ),
															'where' => 't.tid = p.topic_id',
															) ),
								);
																			
		$this->ipsclass->DB->simple_construct( $select );
		$this->ipsclass->DB->simple_order( 'p.pid ASC' );
		$this->ipsclass->DB->simple_exec();
		
		$this->ipsclass->load_template( 'skin_ineo_articles' );
		$posts = '';
		
		while( $post = $this->ipsclass->DB->fetch_row() )
		{
			$post['post_date'] = $this->ipsclass->get_date( $post['post_date'] , '' );
			$posts .= $this->core->templates['articles']->art_post( str_replace( '<#EMO_DIR#>', $this->ipsclass->skin['_emodir'], $post ) );
			$forum_id = $post['forum_id'];
		}

		if ( $this->ipsclass->forums->forum_by_id[ $forum_id ]['read_perms'] == false )
		{
			$this->core->libs['global']->error($this->ipsclass->lang['ineo_perm_error'],$this->ipsclass->lang['ineo_perm_error_text']);
		  	die();
		}
				
		$select = array( 'select' => '*','from'   => 'ineo_articles','where' => 'article_id='.$aid );
																			
		$this->ipsclass->DB->simple_construct( $select );
		$this->ipsclass->DB->simple_exec();
		
		$article = $this->ipsclass->DB->fetch_row();
		
		$topic = $this->core->templates['articles']->art_discussion( $article , $posts );
		$this->send_ajax_response($topic);
	}
	
	function reorder_articles()
	{
		$this->core->load_template('categories');
		$this->core->load_template('articles');

		$cat   = intval($this->ipsclass->input['category']);
		$order = preg_replace('/([^a-zA-Z0-9_]+)/','',$this->ipsclass->input['order_by']);
		$dir   = ( $this->ipsclass->input['order_dir'] == 'ASC' ) ? 'ASC' : 'DESC';
		$page  = intval($this->ipsclass->input['page']); 
		
		$catlib = $this->core->load_library('categories');
		$cat_data = $catlib->load_category_data($cat);
		
		$list = $catlib->display_article_list( $cat, $cat_data , $order . ' ' . $dir, $page );
		
		$list = str_replace('style_images/<#IMG_DIR#>',$this->ipsclass->vars['img_url'],$list);
		
		$this->send_ajax_response($list);
	}
	
	function rate_article()
	{
	  if ( $this->ipsclass->vars['ineo_rating'] == 0 )
	  {
	    die();
	  }
	  
	  $to_rate = intval( $this->ipsclass->input['rating'] );
	  $to_rate = ( $to_rate > 5 ) ? 5 : $to_rate;
	  $to_rate = ( $to_rate < 1 ) ? 1 : $to_rate;
	  
	  $artid = intval( $this->ipsclass->input['artid'] );
	  
	$this->ipsclass->DB->simple_delete( 'ineo_rating', 'rate_artid = '.$artid.' AND rate_mid = '.$this->ipsclass->member['id'] );
    $this->ipsclass->DB->simple_exec();
    
    $this->ipsclass->DB->do_insert( 'ineo_rating', array( 'rate_mid' => $this->ipsclass->member['id'],
                                                         'rate_rating' => $to_rate,
                                                         'rate_artid' => $artid ) );

	if( !empty( $this->ipsclass->input['redir']) )
	{
		$this->ipsclass->boink_it($this->core->base_url . 'showarticle=' . $artid );
	}

    $this->ipsclass->DB->simple_construct( array( 'select' => 'sum( rate_rating ) as rating_total, count( rate_rating ) as rating_count',
                                                  'from' => 'ineo_rating',
                                                  'where' => 'rate_artid = '.$artid ) );
    $this->ipsclass->DB->simple_exec();
    $rate_data = $this->ipsclass->DB->fetch_row();
    
    $rating = $rate_data['rating_total'] / $rate_data['rating_count'];
    $rating = round( $rating, 0 );

	$this->core->load_template('articles');
	
	$rate_box = $this->keyword_replace( $this->core->templates['articles']->rating_box(array('rate_rating' => $to_rate), $rate_data, $this->core->templates['global']->rating_stars($rating)) );
    
    	$this->send_ajax_response($rate_box);
	}
	
	
	function keyword_replace( $string )
	{
		return $this->core->libs['global']->keyword_replace($string);
	}
	
	/**
	* Load the output of an overview plugin.
	*/
	function get_overview_plugin()
	{
		if( !isset($this->ipsclass->input['opid']) )
		{
			die('');
		}
		
		$plug = preg_replace('/([^a-zA-Z0-9\_\- ])/','',$this->ipsclass->input['opid']);
		
		if( file_exists( $this->core->root_path . 'overview_plugins/' . $plug . '.php' ) )
		{
			require_once( $this->core->root_path . 'overview_plugins/' . $plug . '.php' );
			
			$class = 'overview_plugin_' . $plug;
			
			if( $plugin = new $class($this->core) )
			{
				$plugin->plugin_data['is_tab'] = true;
				$data = $this->keyword_replace($plugin->get_data());
				
				$this->send_ajax_response( $data );
			}
			else
			{
				$this->send_ajax_response('Invalid Plugin ID');
			}
		}
		else
		{
			$this->send_ajax_response('Invalid Plugin ID');
		}
	}

	/**
	* This function makes a purdy preview of the article, duhr.
	*/
	function article_preview()
	{
		$text = $this->ipsclass->input['preview'];

		$text = $this->core->api->database_parse($text);
		$text = $this->core->api->display_parse($text,true);

		$this->send_ajax_response($text);
	}
}

?>